package com.wm.eduService.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wm.eduService.entity.EduSubject;
import com.wm.eduService.entity.excel.SubjectData;
import com.wm.eduService.service.EduSubjectService;
import com.wm.servicebase.exceptionhandle.GuliException;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;

import java.util.Objects;

/**
 * @Author: sshdg
 * @Date: 2020/9/29 21:48
 */
@AllArgsConstructor
@NoArgsConstructor
public class SubjectExcelListener extends AnalysisEventListener<SubjectData> {

    /**
     *
     *  因为SubjectExcelListener不能交给Spring管理，需要自己new，不能注入其它对象
     *  不能实现数据库操作
     *  需要手动注入
     */

    private EduSubjectService subjectService;


    @Override
    public void invoke(SubjectData subjectData, AnalysisContext analysisContext) {
        if (subjectData == null){
            throw new GuliException(20001, "文件数据为空！");
        }


        //添加一级科目,不存在，则添加
        EduSubject oneSubject = getOneSubjectByName(subjectService, subjectData.getOneSubjectName());
        if(Objects.isNull(oneSubject)){
            oneSubject  = EduSubject.builder()
                    .parentId("0")
                    .title(subjectData.getOneSubjectName())
                    .build();

            subjectService.save(oneSubject);
        }

        //获取一级科目id
        String parentId = oneSubject.getId();

        EduSubject twoSubject = getTwoSubjectByName(subjectService, subjectData.getTwoSubjectName(), parentId);

        //如果二级科目不存在，则保存
        if(Objects.isNull(twoSubject)){
            twoSubject  = EduSubject.builder()
                    .parentId(parentId)
                    .title(subjectData.getTwoSubjectName())
                    .build();

            subjectService.save(twoSubject);
        }


    }
    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }

    /**
     *  根据名称查询一级科目是否存在
     * @param subjectService
     * @param name  科目名称
     * @return  Subject  科目
     */
    private EduSubject getOneSubjectByName(EduSubjectService subjectService, String name){
        LambdaQueryWrapper<EduSubject> query = new LambdaQueryWrapper<>();
        query.eq(EduSubject::getTitle, name);
        query.eq(EduSubject::getParentId, "0");
        return subjectService.getOne(query);
    }


    /**
     *  根据名称查询二级科目是否存在
     * @param subjectService
     * @param name  科目名称
     * @param pid 一级科目id
     * @return  Subject  科目
     */
    private EduSubject getTwoSubjectByName(EduSubjectService subjectService, String name, String pid){
        LambdaQueryWrapper<EduSubject> query = new LambdaQueryWrapper<>();
        query.eq(EduSubject::getTitle, name);
        query.eq(EduSubject::getParentId, pid);
        return subjectService.getOne(query);
    }
}
